package com.example.compositionlocals

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp

//compositionLocalOf和staticCompositionLocalOf的区别：

//简单概括就是，当我们选择使用 staticCompositionLocalOf 时，
// 实际上创建了个StaticProvidableCompositionLocal 实例，
// 当其所提供的值改变时，会导致 CompositionLocalProvide 内部所有 composable 触发重组(recompose)。
//
//如果我们选择使用 compositionLocalOf，
// 实际上创建了个 DynamicProvidableCompositionLocal 实例，
// 当其所提供的值改变时，仅会导致 CompositionLocalProvide 内部依赖当前 CompositionLocal 的 composable 触发重组(recompose)。
var isStatic = true
var CompositionLocalName = ""

var CurrentLocalColor = if (isStatic) {
    CompositionLocalName = "StaticCompositionLocal 场景"
    staticCompositionLocalOf { Color.Black }
} else {
    CompositionLocalName = "DynamicCompositionLocal 场景"
    compositionLocalOf { Color.Black }
}

var recomposeFlag = "Init"

@Composable
fun CompositionLocalDemo() {
    var color by remember {
        mutableStateOf(Color.Green)
    }
    Box(
        modifier = Modifier
            .fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(text = "${CompositionLocalName}")
            Spacer(modifier = Modifier.height(20.dp))

            CompositionLocalProvider(CurrentLocalColor provides color) {
                TagBox(tag = "Wrapper:${recomposeFlag}", size = 400.dp, background = Color.Red) {
                    TagBox(
                        tag = "Middle:${recomposeFlag}",
                        size = 300.dp,
                        background = CurrentLocalColor.current
                    ) {
                        TagBox(
                            tag = "Inner:${recomposeFlag}",
                            size = 200.dp,
                            background = Color.Yellow
                        )
                    }
                }
            }
            Spacer(modifier = Modifier.height(20.dp))

            Button(
                onClick = { color = Color.Blue }
            ) {
                Text(text = "Change Theme")
            }
        }
    }
    recomposeFlag = "Recompose"
}

@Composable
fun TagBox(tag: String, size: Dp, background: Color, content: @Composable () -> Unit = {}) {
    Column(
        modifier = Modifier
            .size(size)
            .background(background),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(text = tag)
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            content()
        }
    }
}